package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class flashVertificationServlet
 */
@WebServlet("/flashVertificationServlet")
public class flashVertificationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int CONTENTTYPE_LENGTH = 5;
	private static final int ERRORDATA = 1;
	private static final int ZIPDATA = 2;
	private static final String ERRORCODE ="ERROR";
	private static final String ZIPCODE = "ZDATA";
    private static final String INVALID_BINARYDATA = "INVALIDBINARYDATA";
    private static final String VALID_ZIP = "ZIP";
    private static final String VALID_ERROR = "ERROR";
    private static final int TYPECODE_STARTINDEX = 0;
    private static final int TYPECODE_ENDINDEX = 5;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public flashVertificationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		PrintStream out = new PrintStream(response.getOutputStream());
		out.print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
		out.print("<html>");
		out.print("<head>");
		out.print("<title>servelet test</title>");
		out.print("</head>");
		out.print("<body>");
		out.print("asdfasdfasdf");
		out.print("/body");
		out.print("</html>");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	static public void testGenerateZIPByBinaryData(byte[] binaryData,String filename){
		
		File myFile = new File(filename);
		try {
			myFile.createNewFile();

			FileOutputStream fos = new FileOutputStream(myFile);
			fos.write(binaryData);
			fos.flush();
			fos.close();
			
			System.out.println("testGenerateZIPByBinaryData successful!");
		}
		catch (Exception e) {
			System.out.println(e);
			System.out.println("testGenerateZIPByBinaryData fail!");
		}
		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		System.out.println("doPost dealing!");
		
        request.setCharacterEncoding("utf-8");
		
		byte [] binaryData = getBinaryData(request);
		System.out.println(dataAnalysis(binaryData));
          //testFormalPictureZip(request);
        //testCRC(this.getPictureZipBinaryData(request),10005,16);
		
	}
	
	
	private void testCRC(byte[] src,int startIndex,int length){
		
		byte[] CRC = new byte[length];
		for (int i = 0 ; i < length ; ++i){
			
			CRC[i] = src[startIndex+i];
		}
		
		System.out.println(new String(CRC));
		
	}
	private void testFormalPictureZip(HttpServletRequest request) {
		
		byte[] zipData = getPictureZipBinaryData(request);
		
		this.testGenerateZIPByBinaryData(zipData, "c:\\testZIP.zip");
		}
	private byte[] getPictureZipBinaryData(HttpServletRequest request) {
		
		try{
			request.setCharacterEncoding("utf-8");
			
			int dataLength = request.getContentLength();
			if(dataLength > 0 ){
				byte[] result = new byte[dataLength];
				int totalReceived = 0;
				
				ServletInputStream inputStream = request.getInputStream();
				
				while(totalReceived<dataLength) {
					
					int tempReceived = 
							inputStream.readLine(result,totalReceived,dataLength-totalReceived);
						
					totalReceived += tempReceived;
				}
				
				System.out.println("received:"+totalReceived);
				return result;
				
			}
			return null;
			
		}
		catch(Exception e) {
			
			System.out.println(e);
			return null;
		}
		
	}
	
	
	protected byte[] getBinaryData(HttpServletRequest request) {
		int contentLength = request.getContentLength();
		
		if(contentLength > 0 ) {
			
			byte[] binaryData = new byte[contentLength];
			int totalReceived = 0;
			
			try{
				ServletInputStream inputStream = request.getInputStream();
				while(totalReceived<contentLength) {
					
					int tempReceived = 
							inputStream.readLine(binaryData, totalReceived, contentLength-totalReceived);
					
					totalReceived += tempReceived;
				}
				return binaryData;
			}catch (Exception e) {
				
				System.out.println(e);
				return null;
			}
			
		}
		else
		{
			return null;
		}
		
	}
	
	protected String dataAnalysis(byte[] dataBinary){
		
		if(dataBinary == null ||dataBinary.length  < this.CONTENTTYPE_LENGTH){
			return this.INVALID_BINARYDATA;
			
		}else {
			
			//String dataString = new String(dataBinary);
			//String codetype = dataString.substring(this.TYPECODE_STARTINDEX, this.TYPECODE_ENDINDEX);
			byte[] typecode = getTypecodeBytes(dataBinary);
			
			
			
			byte[] contentData = getContentBytes(dataBinary);
			
			
			return dataService(new String(typecode), contentData);
			
		}
		
	}
	protected byte[] getTypecodeBytes(byte[] src){
		if( src==null || src.length < this.CONTENTTYPE_LENGTH ){
			
			return null;
		}else {
			
			byte[] codetype = new byte[this.CONTENTTYPE_LENGTH];
			int counter = 0;
			
			while(counter < this.CONTENTTYPE_LENGTH) {
				
				codetype[counter] = src[counter];
				++counter;
			}
			return codetype;
			
		}
	}
	
	protected byte[] getContentBytes(byte[] src){
		if( src==null || src.length < this.CONTENTTYPE_LENGTH ){
			
			return null;
		}else {
			
			int srcLength = src.length - this.CONTENTTYPE_LENGTH;
			byte[] contentBytes = new byte[srcLength];
			int counter = 0;
			
			while(counter < srcLength) {
				
				contentBytes[counter] =src[counter+this.CONTENTTYPE_LENGTH];
				++counter;
			}
			return contentBytes;
			
		}
	}
	protected String  dataService(String typecode, byte[] src){
		
		if(this.ZIPCODE.equals(typecode)){
			
			testGenerateZIPByBinaryData(src, "c:\\testGenerateZip.zip");
			//System.out.println(new String(src));
			return this.VALID_ZIP;
			
		}else if(this.ERRORCODE.equals(typecode)) {
		
			System.out.println(new String(src));
			return this.VALID_ERROR;
		}
		else {
			
			//System.out.println("unknown typecode");
			return "unknown typecode";
		}
	}
	
	protected int  getBinaryDataByCode(HttpServletRequest request , String code){
		
		if(code ==  null ){
			return -1;
		}
		else {
			
			if(code.equals(ERRORCODE)){
				
				//log error
				
				return this.ERRORDATA;
			}
			else if(code.equals(ZIPCODE)){
					
					System.out.println("before getting zipData -----requestContentLength:"+request.getContentLength());
					
					int dataLength = request.getContentLength()- code.length();
					byte[] zipBinaryData = new byte[dataLength];
					
					int currentOffsetInStream = code.length();
					int totalReceived = 0;
					
					try{
						ServletInputStream inputStream = request.getInputStream();
						
						while(totalReceived<dataLength) {
							
							int tempReceived = 
									inputStream.readLine(zipBinaryData, currentOffsetInStream, dataLength-totalReceived);
							
							currentOffsetInStream += tempReceived;
							totalReceived += tempReceived;
						}
						
						System.out.println("length:"+dataLength+"             totalReceived:"+totalReceived);
						System.out.println(new String(zipBinaryData));
						
						testGenerateZIPByBinaryData(zipBinaryData,"c:\\testGenerateZip.zip");
					}catch(Exception e) {
						
						System.out.println(e);
					}finally {
						return this.ZIPDATA;
					}
				
				}
			else{
				return -1;
			}
		}
		
	}
	
	protected String getContentCode(HttpServletRequest request){
		
		String contentCode = null;
		byte[] contentBinary = new byte[5];
		
		System.out.println("before getting code-----requestTotalContentLength:"+request.getContentLength());
		try{
		int receiveCounter = request.getInputStream().readLine(contentBinary, 0, CONTENTTYPE_LENGTH);
		
		if(receiveCounter > 0){
			
			contentCode = new String(contentBinary);
		}
		}catch(Exception e){
			
			System.out.println(e);
		}
		
		System.out.println(contentCode);
		return contentCode;
		
	}

}
